<?php

namespace app\admin\controller;

use app\lib\enum\Status;
use think\Exception;
use think\Log;
use think\Request;

class Information extends BaseController
{



    //地区管理
    public function locationList()
    {
        if (request()->isAjax()) {
            //没有page分页，直接显示全部数据
            $condition = [];
            $condition['attr_type'] = Status::location;
            $locationList = model("PyAttr")->where($condition)
                ->order("attr_order", "asc")
                ->select();
            $count = count($locationList);
            return getJson($count, $locationList);

        }
        return view();
    }

    //地区添加
    public function locationAdd()
    {
        if (request()->isAjax()) {
            $this->uniteResponse(model("PyAttr")->addData(Request::instance()->param(), "该地区已存在"), "地区添加成功");
        }
        return view();
    }

    //地区编辑
    public function locationEdit()
    {
        $attr_id = input("get.primary_id");
        if (request()->isAjax()) {
            $this->uniteResponse(model("PyAttr")->editData(Request::instance()->param(), $attr_id, "该地区已存在"), "地区编辑成功");
        }

        //页面数据渲染
        $locationInfo = model("PyAttr")->where("attr_id", "=", $attr_id)->find();
        $this->assign("locationInfo", $locationInfo);
        return view();
    }


    //年份管理
    //地区管理
    public function yearList()
    {
        if (request()->isAjax()) {
            //没有page分页，直接显示全部数据
            $condition = [];
            $condition['attr_type'] = Status::year;
            $yearList = model("PyAttr")->where($condition)
                ->order("attr_order", "asc")
                ->select();
            $count = count($yearList);
            return getJson($count, $yearList);

        }
        return view();
    }

    //地区添加
    public function yearAdd()
    {
        if (request()->isAjax()) {
            $this->uniteResponse(model("PyAttr")->addData(Request::instance()->param(), "该年份已存在", Status::year), "年份添加成功");
        }
        return view();
    }

    //地区编辑
    public function yearEdit()
    {
        $attr_id = input("get.primary_id");
        if (request()->isAjax()) {
            $this->uniteResponse(model("PyAttr")->editData(Request::instance()->param(), $attr_id, "该年份已存在"), "年份编辑成功");
        }

        //页面数据渲染
        $yearInfo = model("PyAttr")->where("attr_id", "=", $attr_id)->find();
        $this->assign("yearInfo", $yearInfo);
        return view();
    }


    //招生信息导入分类页面
    public function informationCategoryList(){
        if(request()->isAjax()){
            $page=input("get.page");
            $limit=input("get.limit");
            $yearId=input("get.yearId");
            $locationId=input("get.locationId");
            //争对不同的限制条件，修改搜索条件
            $condition=[];
            //设置分类为：信息分类数据
            $condition['attr_type']=['eq',Status::info];

            if($yearId!=null&&$yearId!=-1){
                $condition['attr_value']=['eq',$yearId];
            }
            if($locationId!=null&&$locationId!=-1){
                $condition['attr_name']=['eq',$locationId];
            }
            //渲染页面数据
            $categoryList=model("PyAttr")->with("bindLocation,bindYear")
                ->where($condition)
                ->select();
            foreach ($categoryList as &$value){
                $value['year']=$value['bind_year']['attr_name'];
                $value['location']=$value['bind_location']['attr_name'];
            }
            $count=model("PyAttr")->getCount($condition);
            return getJson($count,$categoryList);
        }

        //文章所属年份和所属地区信息渲染到页面上
        $yearList = model("PyAttr")->where("attr_type", "=", Status::year)
            ->order("attr_order", "asc")
            ->select();
        $this->assign("yearList", $yearList);

        $locationList=model("PyAttr")->where("attr_type","=",Status::location)
            ->order("attr_order","asc")
            ->select();
        $this->assign("locationList",$locationList);
        return view();
    }



    //分类信息添加
    public function informationCategoryAdd(){
        if(request()->isAjax()){
            //获取数据并进行数据添加
            $this->uniteResponse(model("PyAttr")->addCategory(Request::instance()->param()),"信息添加成功");
        }
        //文章所属年份和所属地区信息渲染到页面上
        $yearList = model("PyAttr")->where("attr_type", "=", Status::year)
            ->order("attr_order", "asc")
            ->select();
        $this->assign("yearList", $yearList);
        $locationList=model("PyAttr")->where("attr_type","=",Status::location)
            ->order("attr_order","asc")
            ->select();
        $this->assign("locationList",$locationList);
        return view();

    }
    //分类信息编辑
    public function informationCategoryEdit(){
        if(request()->isAjax()){
            //获取数据并进行数据编辑修改
            $this->uniteResponse(model("PyAttr")->editCategory(Request::instance()->param()),"信息编辑成功");
        }



        //获取分类id，根据id查找当前分类信息，展示于页面
        $attr_id=input("get.attr_id");
        $categoryInfo=model("PyAttr")->where("attr_id","=",$attr_id)->find();
        $this->assign("categoryInfo",$categoryInfo);

        //文章所属年份和所属地区信息渲染到页面上
        $yearList = model("PyAttr")->where("attr_type", "=", Status::year)
            ->order("attr_order", "asc")
            ->select();
        $this->assign("yearList", $yearList);
        $locationList=model("PyAttr")->where("attr_type","=",Status::location)
            ->order("attr_order","asc")
            ->select();
        $this->assign("locationList",$locationList);

        return view();
    }


    //Excel导入
    public function informationAddByExcel(){
        if(request()->isAjax()){
            //获取该信息分类
            $attr_id=input("get.attr_id");
            //获取所上传Excel文件
            $file=Request::instance()->file("file");
            $checkFile=$file->validate(['ext' => 'xls,xlsx']);
            //从Excel文件中获取数据
            //如果发生异常，就提示用户
            try{
                $fileData=$this->handleExcel($file);
                if($fileData===false){
                    $this->error("文件类型错误，请使用Excel模板导入数据");
                }
            }catch (Exception $e){
                $this->error("系统异常，请联系开发人员","",$e->getMessage());
                return false;
            }
            $this->uniteResponse(model("PyAdmissionInformation")->inputExcel($attr_id,$fileData),"信息导入成功");
        }
        return view();
    }


    //清空指定分类下的数据信息
    public function deleteInformation(){
        if(!session("adminInfo")){
            $this->error("无权限删除");
        }
        $this->uniteResponse(model("PyAdmissionInformation")->deleteInformation(Request::instance()->param()),"数据清除成功");
    }


    //招生信息详情页面
    public function informationDetailList()
    {
        //显示信息
        if(request()->isAjax()){
            $page=input("get.page");
            $limit=input("get.limit");
            $yearId=input("get.year");
            $locationId=input("get.location");
            //争对不同的限制条件，修改搜索条件
            $condition=[];
            //py_admission_information
            if($yearId!=null&&$yearId!=-1){
                $condition['ain_year_id']=['eq',$yearId];
            }
            if($locationId!=null&&$locationId!=-1){
                $condition['ain_location_id']=['eq',$locationId];
            }

            $informationList=model("PyAdmissionInformation")->with("bindLocation,bindYear")
                ->where($condition)
                ->page($page,$limit)
                ->select();
            foreach ($informationList as &$value){
                $value['location']=$value['bind_location']['attr_name'];
                $value['year']=$value['bind_year']['attr_name'];
            }

            $countData=model("PyAdmissionInformation")->where($condition)->field("count(*)")->select();
            $count=$countData[0]['count(*)'];
            return getJson($count,$informationList);
        }
        //获取数据
        $year=input("get.year");
        $location=input("location");
        //加载到页面上，用来异步请求的时候作为参数
        $this->assign("year",$year);
        $this->assign("location",$location);
        return view();
    }

    //下面三个方法用来处理excel相关数据
    //其他地方用不到
    public function handleExcel($file) {
        //获取表单上传文件
        $filePath=ROOT_PATH . 'public' . DS . 'uploads' . DS . "excel";
        if(!is_dir($filePath)){
            @mkdir($filePath);
        }
        $info = $file->validate(['ext' => 'xls,xlsx'])->move($filePath);
        $excelData = [];
        if ($info) {
            $excelPath = $info->getSaveName();//获取文件名
            $file_name = $filePath . DS . $excelPath;    //上传文件的地址
            $excelData = $this->getDataFromExcel($file_name);
            try{
                unlink($file_name);
            }catch (Exception $e){

            }
            return $excelData;
        }else{
            return false;
        }

    }
    public function getDataFromExcel($file_name) {
        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $extension = $this->get_extension($file_name);
        if ($extension == "xlsx") {
            //2007版本
            $objReader = \PHPExcel_IOFactory::createReader("Excel2007");
        } else {
            $objReader = \PHPExcel_IOFactory::createReader("Excel5");
        }
        $obj_PHPExcel = $objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8
        $excel_array = $obj_PHPExcel->getSheet(0)->toArray();   //转换为数组格式
        $data = [];
        foreach ($excel_array as $key=>$value) {
            //去掉第一行数据
            if($key>0){
                if ($value[0] != null && $value[0] != "") {
                    $data[] = $value;
                }
            }
        }
        return $data;
    }
    public function get_extension($filename) {
        return pathinfo($filename, PATHINFO_EXTENSION);
    }

    //下载记录相关
    public function logList(){
        if(request()->isAjax()){
            $condition=[];
            $page=input("get.page");
            $limit=input("get.limit");
            $sloPayStatus=input("get.sloPayStatus");
            $timeStart=input("get.timeStart");
            $timeEnd=input("get.timeEnd");
            if($sloPayStatus!=""&&$sloPayStatus!=-1){
                $condition['slo_pay_status']=$sloPayStatus;
            }
            //处理支付时间的过滤
            $this->handleTime($condition,$timeStart,$timeEnd);

            $count=getCount("PySearchLog",$condition);

            $logData=model("PySearchLog")->with("bindLocation")
                ->where($condition)
                //按照时间倒叙
                ->order("slo_id","desc")
                ->page($page,$limit)
                ->select();
            foreach ($logData as &$value){
                $value['pay_status']=$this->getPayStatus($value['slo_pay_status']);
                $value['location']=$value['bind_location']['attr_name'];
                $value['year']=$value['bind_year']['attr_name'];
                $value['slo_create_time']=date("Y-m-d H:i:s",$value['slo_create_time']);
            }
            return getJson($count,$logData);
        }
        //将系统设置好的支付状态渲染到页面上
        //   const noPay=1;
        //    const paySuccess=2;
        //    const payFail=3;
        $payStatus=[
            "noPay"=>Status::noPay,
            "paySuccess"=>Status::paySuccess,
            "payFail"=>Status::payFail,
            "freeGet"=>Status::freeGet
        ];
        $this->assign("payStatus",$payStatus);
        return view();
    }

    //下载记录详情
    public function logDetail(){
        //获取主键
        $slo_id=input("get.primary_id");
        $logInfo=model("PySearchLog")->with("bindLocation,bindYear")
            ->where("slo_id","=",$slo_id)
            ->find();
        $logInfo['slo_create_time']=date("Y-m-d H:i:s",$logInfo['slo_create_time']);
        $logInfo['slo_pay_status']=$this->getPayStatus($logInfo['slo_pay_status']);
        $fields=model("PySearchLog")->getTableFields();
        foreach ($fields as $field) {
            if($logInfo[$field]==""){
                $logInfo[$field]="未填写该搜索条件";
            }
        }
        $this->assign("logInfo",$logInfo);
        return view();
    }

    //处理时间
    public function handleTime(&$condition,$timeStart,$timeEnd){
        //因为strtotime有些环境下会报错，因此需要捕获异常，并设置默认值
        try{
            $timeStart=$timeStart!=""?strtotime($timeStart):false;
        }catch (Exception $e){
            $timeStart=config("setting.minTime");
        }

        try{
            $timeEnd=$timeEnd!=""?strtotime($timeEnd):false;
        }catch (Exception $exception){
            $timeEnd=config("setting.maxTime");
        }
        if($timeStart&&$timeEnd){
            $condition['slo_create_time']=['between',$timeStart.",".$timeEnd];
        }
        if($timeStart||$timeEnd){
            $timeStart?$condition['slo_create_time']=['>',$timeStart]:true;
            $timeEnd?$condition['slo_create_time']=['<',$timeEnd]:true;
        }
    }

    //处理支付状态
    public function getPayStatus($slo_pay_status){
        switch ($slo_pay_status){
            case Status::noPay:
                return "未支付";
                break;
            case Status::paySuccess:
                return "支付成功";
                break;
            case Status::payFail:
                return "支付失败";
                break;
            case Status::freeGet:
                return "免费查询";
                break;
        }
    }

    //查看用户信息
    public function getUserInfo(){
        $usr_id=input("get.usr_id");
        $userInfo=model("PyUser")->where("usr_id","=",$usr_id)->find();
        $this->assign("userInfo",$userInfo);
        return view();
    }

    


}
